# -*- coding:utf-8 -*-
import base64
import json

from PIL import Image
from io import BytesIO
from web import RequestHandler
from tornado.websocket import WebSocketHandler
import tornado.ioloop
import numpy as np  #矩阵算法库

from com.py.test.face_recogn.FaceRecognPhoto import FaceRecognPhoto

def toNumpyArray(im, mode='RGB'):
    # im = Image.open(BytesIO(data))
    if mode:
        im = im.convert(mode)
    return np.array(im)

class MainHandler(RequestHandler):
    local_dir = "D://picture/upload_face/"
    def post(self):
        self.set_header("Access-Control-Allow-Origin", "*");#允许所有域跨域请求
        self.set_header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE,PUT");# 跨域请求的类型
        self.set_header("Access-Control-Max-Age", "3600");# 跨域生命周期
        self.set_header("Access-Control-Allow-Headers", "x-requested-with");# 跨域数据响应方式

        """post"""
        data = self.get_argument('data')
        data = base64.b64decode(data)  #解码base64
        new_im = Image.open(BytesIO(data))
        data = toNumpyArray(new_im)
        img_data = FaceRecognPhoto().recognFace(data)
        # w_img = Image.fromarray(img)
        # w_img.show()
        # resContent = "result:"+img
        # print(str(img))
        result = {}
        if not img_data =={}:
            result.__setitem__("code","success")
        else:
            result.__setitem__("code","error")
        result.__setitem__("data",img_data)
        print(result)
        self.write(result)


users = set()
class ChatHandler(WebSocketHandler):
    def check_origin(self, origin: str):
        return True
    def open(self, *args, **kwargs):
        '''客户端连接'''
        print("connect....")
        users.add(self)
    def on_message(self, message):
        '''有消息到达'''
        for client in users:
            if client == self: #给自己发消息
                client.write_message(self.face_recorgn(message))
                break;
           # 给其他人发 client.write_message(message)
    def on_close(self):
        '''客户端主动关闭连接'''
        users.remove(self)

    def face_recorgn(self,data):
        data = base64.b64decode(data)  #解码base64
        new_im = Image.open(BytesIO(data))
        data = toNumpyArray(new_im)
        img_data = FaceRecognPhoto().recognFace(data)

        result = {}
        if not img_data =={}:
            result.__setitem__("code","success")
        else:
            result.__setitem__("code","error")
        result.__setitem__("data",img_data)
        return result
class IndexHandler(RequestHandler):
    def get(self):
        self.write("Hello, world")

application =  tornado.web.Application([(r"/face/", IndexHandler),(r"/face/recognFace", MainHandler)
                                           ,(r"/face/chat", ChatHandler)])


if __name__ == "__main__":
    application.listen(8088)
    tornado.ioloop.IOLoop.instance().start()
